import pypinyin
import os,re,json
from multiprocessing import Pool
import shutil

def convert(file,kbps,name):
    os.system('ffmpeg -y -loglevel quiet -i "music/'+file+'" -acodec libvorbis -ab '+kbps+'k -vn "rp/sounds/music/'+name+'.ogg"')
    print('转码完成:'+file+"=>"+name+".ogg")

def cnm(mode,kbps,size):
    if not (int(kbps)<1000 and int(kbps)>80):
        kbps='128'
    suc=0
    failList=[]
    list = os.listdir('./music/')
    for file in list:
        name=file.split('.')[0]
        name=''.join(pypinyin.lazy_pinyin(name,style=pypinyin.Style.FIRST_LETTER))
        name= name.replace("-","_")
        for ii in "()&*$#@%+-;:\'\"\\/ ＜：「ー!」[]，":
            name=name.replace(ii,"")
        name = re.search(r"^[\u4E00-\u9FA5A-Za-z0-9_]+$",name)
        if name:
            name=name.group()
            if mode:
                # 转码
                pool.apply_async(func=convert,args=(file,kbps,name))
                # 获取音乐标签信息
                data=os.popen(f'ffprobe -v quiet -show_format -print_format json "./music/{file}"')
                jsondata=json.loads(data.buffer.read().decode('utf-8'))
                # 获取专辑信息
                album=jsondata['format']['tags']['album']
                album=''.join(pypinyin.lazy_pinyin(album,style=pypinyin.Style.NORMAL))
                # 删除特殊字符
                for ii in "()?&*$#@%+-;:\'\"\\/ ＜：「ー!」[]，?":
                    album=album.replace(ii,"")
                # 提取专辑图片
                os.system('ffmpeg -y -loglevel quiet -i "music/'+file+f'" -vf scale={size}:{size} "rp/textures/album/'+album+'.png"')
            suc=suc+1
        else:
            failList.append(file)
    return suc,failList
if __name__=='__main__':
    result=cnm(False,128,800)
    failList=result[1]
    print("_______________________\n检测完成,名字合格:"+str(result[0])+"个音频，不合格"+str(len(failList))+"个，\n--------不合格列表--------")
    for i in failList:
        print(i)
    y=input("是否继续(y/n):")
    if y=="y":
        try:
            with open("./config.json","r",encoding="utf8") as f:
                config=json.loads(f.read())
                if(config['thread']<1 or config['thread']>12):
                    raise Exception("线程数错误")
                if not (100<int(config['size']) and int(config['size'])<2000):
                    raise Exception("封面大小错误")
                if(config['kbps']<80 or config['kbps']>1000):
                    raise Exception("比特率错误")
        except Exception as e:
            print("配置文件错误:",e)
            config={"thread":4,"kbps":"128","size":"800"}
        thread=int(config['thread'])
        pool=Pool(thread)
        kbps=str(config['kbps'])
        size=str(config['size'])
        print("清理文件夹")
        shutil.rmtree("./rp/sounds/music/")
        shutil.rmtree("./rp/textures/album/")
        os.mkdir('./rp/sounds/music/')
        os.mkdir('./rp/textures/album/')
        print(f"开始转换,进程:{thread},比特率:{kbps},封面大小:{size}x{size}")
        cnm(True,kbps,size)
        pool.close()
        pool.join()
        list1=os.listdir("./music/")
        list2=os.listdir("./rp/sounds/music/")
        print("转换完成,共转换:"+str(len(list2))+"，失败:"+str(len(list1)-len(list2)))

